package servlet;

import bean.Student;
import utils.DBUtil;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

@WebServlet("/add")
public class AddServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        ArrayList<Student> list = new ArrayList<>();
        String sql ="select * from attence a , student s   where a.sid=s.sid";
        ResultSet rs = DBUtil.query(sql);
        try {
            while (rs.next()){
                int sid = rs.getInt("sid");
                String sName = rs.getString("sName");
                Student student = new Student(sid, sName);
                list.add(student);

            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        request.setAttribute("list",list);

        request.getRequestDispatcher("/WEB-INF/form.jsp").forward(request,response);

    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        request.setCharacterEncoding("utf-8");

        String sid = request.getParameter("sid");

        String time = request.getParameter("time");
        String type = request.getParameter("type");
        String sql = "insert into attence values(?,?,?,?)";
        int i = DBUtil.update(sql, null, time, type, sid);

        if (i>0){
            // response.sendRedirect("/car");
            request.setAttribute("msg","添加成功");
            request.getRequestDispatcher("/WEB-INF/msg.jsp").forward(request,response);
        }else{
            request.setAttribute("msg","添加失败");
            request.getRequestDispatcher("/WEB-INF/msg.jsp").forward(request,response);
        }


    }
}
